/*
 *
 *  Copyright (C) 2010 Tal Eisenberg
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package tal.drivechain.expression;

import java.text.DecimalFormat;
import tal.drivechain.chain.Chain;
import tal.drivechain.chain.ChainNode;
import tal.drivechain.midi.MidiUtility;
import tal.drivechain.parsing.UnitParser;
import tal.drivechain.system.Globals;

/**
 *
 * @author eisental
 */
public class DrivechainFunctions {
    public static ChainNode node(Chain parentChain, String nodeName) {
        ChainNode n = parentChain.getChildNodes().get(nodeName);
        if (n==null) throw new IllegalArgumentException("Unknown module " + nodeName + " in chain " + parentChain);
        else return n;
    }

    public static Chain chain(String chainName) {
        return Globals.findChain(chainName, null);
    }

    public static Object prop(Chain parentChain, String nodeName, String property) {
        ChainNode n = DrivechainFunctions.node(parentChain, nodeName);
        Object p = n.getProperty(property);
        return p;
    }

    public static String noteName(int note) {
        return MidiUtility.noteNumberToString(note);
    }

    public static int note(String noteName) {
        return MidiUtility.stringToNoteNumber(noteName);
    }

    public static String commandName(int command) {
        return MidiUtility.commandCodeToString(command);
    }

    public static double toUnit(double val, String unit) {
        double unitval = UnitParser.applyUnits(val, UnitParser.parseUnitStack(unit));
        if (unitval==Math.rint(unitval)) //integer
            return unitval;
        else return unitval;
    }

    public static double unit(double val, String unit) {
        double unitval = UnitParser.UnitsToVal(val, UnitParser.parseUnitStack(unit));
        return unitval;
    }

    public static String format(Object val, String format) {
        DecimalFormat f = new DecimalFormat(format);
        return f.format(val);
    }

}
